#include "wav-file.h"
#include <string.h>
#include <stdio.h>

wavFile::wavFile(const string &filename) : filename(filename)
{
    // 固定字段
    strncpy(header.riff_tag, "RIFF", 4);
    strncpy(header.wave_tag, "WAVE", 4);
    strncpy(header.fmt_tag, "fmt ", 4);
    strncpy(header.data_tag, "data", 4);
}

/// @brief 设置文件头
/// @param sampleRate 采样频率 美妙采样多少次
/// @param channels  通道数
/// @param sampleBits 样本位深
void wavFile::setParams(int sampleRate, int channels, int sampleBits)
{
    header.fmt_length = 16;
    header.audio_format = 1;
    header.num_channels = channels;
    header.sample_rate = sampleRate;
    header.byte_rate = sampleRate * channels * sampleBits / 8;
    header.block_align = sampleBits * channels / 8;
    header.bits_per_sample = sampleBits;
}

bool wavFile::writeData(uint8_t *data, uint32_t size)
{
    FILE *fp = fopen(filename.c_str(), "w");
    if (!fp)
    {
        fprintf(stderr, "FAIL to open  :%s :%s", filename.c_str(), strerror(errno));
        return false;
    }
    // 写头
    header.riff_length = sizeof(wavfile_header_t) - 8 + size;
    header.data_length = size;
    int ret = fwrite(&header, sizeof(uint8_t), sizeof(header), fp);
    if (ret != sizeof(header))
    {
        fclose(fp);
        fprintf(stderr, "FAIL to fwrite header :%s ", strerror(errno));
        return false;
    }
    // 写 pcm data
    ret = fwrite(data, sizeof(uint8_t), size, fp);
    if (ret != sizeof(header))
    {
        fclose(fp);
        fprintf(stderr, "FAIL to fwrite pcm data :%s ", strerror(errno));
        return false;
    }

    fclose(fp);
    return true;
}
